﻿using System;
using System.IO;
using UnityEngine;

/// <summary>
/// 文件操作处理类
/// </summary>
public class FileIO
{
    // 创建文件目录
    public static bool CreateFolder(string folder)
    {
        try
        {
            DirectoryInfo info = Directory.CreateDirectory(folder);
            return info != null;
        }
        catch (Exception exp)
        {
            Debug.Log(exp.ToString());
        }
        return false;
    }

    // 删除文件目录
    public static bool DeleteFolder(string folder)
    {
        try
        {
            //Directory.Delete(folder, true);
            return true;
        }
        catch (Exception exp)
        {
            Debug.Log(exp.ToString());
        }
        return false;
    }

    // 删除文件
    public static bool DeleteFile(string fileName)
    {
        try
        {
            File.Delete(fileName);
            return true;
        }
        catch (Exception exp)
        {
            Debug.Log(exp.ToString());
        }
        return false;
    }

    // 二进制方式读取文件操作
    public static byte[] ReadFile(string fileName, ref int len)
    {
        // 判断文件是否存在
        if (!File.Exists(fileName))
        {
            len = 0;
            return null;
        }
        try
        {
            // 读取文件
            FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(file);

            len = (int)file.Length;
            byte[] buffer = new byte[len];
            reader.Read(buffer, 0, len);

            reader.Close();
            file.Close();
            return buffer;
        }
        catch (Exception exp)
        {
            Debug.Log(exp.ToString());
        }
        len = -1;
        return null;
    }

    // 二进制文件写入操作
    // 仅仅支持在平台可写目录进行写入操作
    // 每次写入都是完全覆盖写入(之前内容被清空)
    public static bool WriteFile(string fileName, byte[] buffer, int length)
    {
        try
        {
            // 打开文件，没有则新创建
            FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            if (file == null) { return false; }

            BinaryWriter writer = new BinaryWriter(file);
            writer.Write(buffer, 0, length);
            writer.Close();

            file.Close();
            return true;
        }
        catch (Exception exp)
        {
            Debug.Log(exp.ToString());
        }
        return false;
    }
}